package org.wlgzs.office_exam_student.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.wlgzs.office_exam_student.dao.BaseDao;
import org.wlgzs.office_exam_student.entity.ChoiceQuestion;
import org.wlgzs.office_exam_student.entity.ExamQuestion;

/**
*@author song(mejeesong@qq.com)
*2018年2月5日
*
*/
public class ExamQuestionService extends BaseDao<ExamQuestion> {
	
	private final ChoiceQuestionService cqs = new ChoiceQuestionService();
	
	/**
	*@author song(mejeesong@qq.com)
	*@date 2018年2月5日
	*@param examId
	*@return 一个集合，共同包含ChoiceQuestion and OperateQuestion
	*
	*/
	public List<ExamQuestion> getQuestions(int examId) {
		String sql = "select * from tb_exam_question where exam_id = "+examId;
		List<ExamQuestion> examQuestions = exec( qr -> {
			try {
				return qr.query(sql, BEAN_LIST_HANDLER);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return null;
		});
		return examQuestions;
		/*
		if(examQuestions != null) {
			boolean hasChoice = false;
			boolean hasOperate = false;
			StringBuilder choiceId = new StringBuilder("( ");
			StringBuilder operationId = new StringBuilder("( ");
			for(ExamQuestion eq:examQuestions) {
				if(ExamQuestion.TYPE_CHOICE.equals(eq.getType())) {
					hasChoice = true;
					choiceId.append(eq.getId()).append(",");
				}else if(ExamQuestion.TYPE_CHOICE.equals(eq.getType())){
					hasOperate = true;
					operationId.append(eq.getId()).append(",");
				}
			}
			if(hasChoice) {
				choiceId.deleteCharAt(choiceId.length() -1);
				choiceId.append(')');
				String sql1 = "select * from tb_choice_question where id in "+choiceId.toString();
				List<ChoiceQuestion> choices = cqs.exec( qr -> {
					try {
						return qr.query(sql1, BEAN_LIST_HANDLER);
					} catch (SQLException e) {
						e.printStackTrace();
						return null;
					}
				});
				if(choices != null) {
					for(ChoiceQuestion cq:choices) {
						results.add(cq);
					}
				}
			}
			if(hasOperate) {
				operationId.deleteCharAt(operationId.length() -1);
				operationId.append(')');
				String sql2 = "select * from tb_operate_question where id in "+operationId.toString();
				List<OperateQuestion> operates = oqs.exec( qr -> {
					try {
						return qr.query(sql2, BEAN_LIST_HANDLER);
					} catch (SQLException e) {
						e.printStackTrace();
						return null;
					}
				});
				
				if(operates != null) {
					for(OperateQuestion oq:operates) {
						results.add(oq);
					}
				}
			}
		}
		return results;
		*/
		
	}

	//选择题集合
	public List<ChoiceQuestion> choiceQuestions(List<ExamQuestion> examQuestions){

		List<ChoiceQuestion> choiceQuestions=new ArrayList<>();
		for(ExamQuestion examQuestion : examQuestions){
			if(ExamQuestion.TYPE_CHOICE.equals(examQuestion.getType())){
				choiceQuestions.add(cqs.choiceQuestion(examQuestion.getQuestionId()));
			}
		}
		Collections.shuffle(choiceQuestions);
		return choiceQuestions;
	}

}
